package com.ruike.alisurface.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ruike.alisurface.R;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.serialport.MsgEventBus;
import com.ruike.alisurface.serialport.QrCodeUtils;
import com.ruike.alisurface.ui.adapters.QrCodeAdapter;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_utils.SharedUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

public class QrCode_Aty extends BaseAty implements ApiListener {


    List<String> codes = new ArrayList<>();
    StringBuilder sbfcode = new StringBuilder();//条码
    Timer qrcodeTimer;//反扫的指令计时
    TimerTask qrTimerTask;
    int CommandCount = 0;//发送指令的次数
    @BindView(R.id.qrcode_goback_imgv)
    ImageView qrcodeGobackImgv;
    @BindView(R.id.qrcode_time_tv)
    TextView qrcodeTimeTv;
    @BindView(R.id.qhcode_number_tv)
    TextView qhcodeNumberTv;
    @BindView(R.id.qhcode_clear)
    TextView qhcodeClear;
    @BindView(R.id.qhcode_gridView)
    GridView qhcodeGridView;
    @BindView(R.id.qrcode_alter_tv)
    TextView qrcode_alter_tv;
    @BindView(R.id.code_ly)
    LinearLayout codeLy;
    @BindView(R.id.fscode_img)
    ImageView fscode_img;

    @Override
    protected int getLayoutResId() {
        return R.layout.app_doctor_qrcode;
    }

    @Override
    protected void initViews() {
        startCountdownTimer(60, qrcodeTimeTv, ShopMain_Aty.class);
        initTitleBar(false);
        boolean medicine_is_scan = SharedUtils.getInstance().getBoolean(ShareKey.medicine_is_scan, false);
        String medicine_scan_alert = SharedUtils.getInstance().getString(ShareKey.medicine_scan_alert, "");
        if (!medicine_scan_alert.equals("null") && !TextUtils.isEmpty(medicine_scan_alert)) {
            qrcode_alter_tv.setText(medicine_scan_alert);
        }
        if (medicine_is_scan) {
            fscode_img.setVisibility(View.VISIBLE);

            qrcodeTimer = new Timer();
            qrTimerTask = new TimerTask() {
                @Override
                public void run() {
                    if (CommandCount > 2) {
                        qrcdoeCancal();
                        return;
                    }
                    QrCodeUtils.sendCommandCode();
                    CommandCount++;
                }
            };
            qrcodeTimer.schedule(qrTimerTask, 100, 20100);
        } else {
            fscode_img.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        codes.add("1");
        codes.add("2");
        codes.add("3");
        codes.add("4");
        codes.add("5");
        codes.add("6");
        codes.add("7");
        codes.add("8");
        codes.add("9");
        codes.add("删除");
        codes.add("0");
        codes.add("确认");



        qrcodeGobackImgv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(ShopMain_Aty.class, null);
                finish();
            }
        });
        qhcodeClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sbfcode.delete(0, sbfcode.length());
                qhcodeNumberTv.setText("");
            }
        });
        QrCodeAdapter qrCodeAdapter = new QrCodeAdapter(this, codes);
        qhcodeGridView.setAdapter(qrCodeAdapter);
        qhcodeGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                L.i("tjf=codes=" + position);
                if (codes.get(position).equals("删除")) {
                    if (sbfcode.length() > 0) {
                        sbfcode.delete(sbfcode.length() - 1, sbfcode.length());
                        qhcodeNumberTv.setText(sbfcode.toString());
                    }
                } else if (codes.get(position).equals("确认")) {
                    if (sbfcode.length() >= 4) {
                        if (!isQrCode) {
                            isQrCode = true;
                            showProgressDialog("正在确认条码中，请等待。。。");
                            L.i("tjf=codes确认=" + sbfcode.toString());
                            doctor_bar_code = sbfcode.toString();
                            showcodeAlt();
                        }
                    } else {
                        showErrorLongToast("条码长度太短，请重新输入", 5000);
                    }
                } else {
                    if (sbfcode.length() >= 18) {
                        showErrorToast("条码长度已到最大值，无法输入");
                        return;
                    }
                    sbfcode.append(codes.get(position));
                    qhcodeNumberTv.setText(sbfcode.toString());
                }
            }
        });
    }

    boolean isQrCode;
    String doctor_bar_code;

    @Override
    public void onEventBusResult(MsgEventBus event) {
        super.onEventBusResult(event);
        if (event.getType().equals("扫码code")) {
            if (!isQrCode) {
                isQrCode = true;
                doctor_bar_code = event.getMessage();
                showProgressDialog("正在请求中，请等待。。。");
                showcodeAlt();
            }
        }

    }

    /**
     * 生成订单信息
     */
    private void showcodeAlt() {
        try {

        } catch (Exception e) {
            L.i("pay====error==", e.getLocalizedMessage());
        }
    }

    @Override
    public void onRequestStart(String requestUrl, int requestId) {

    }

    @Override
    public void onRequestComplete(String requestUrl, int requestId) {

    }

    @Override
    public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {

    }

    @Override
    public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {

    }

    @Override
    protected void onStop() {
        super.onStop();
        qrcdoeCancal();
    }

    public void qrcdoeCancal() {
        L.i("取消计时发送识别扫码指令");
        if (qrTimerTask != null) {
            qrTimerTask.cancel();
            qrTimerTask = null;
        }
        if (qrcodeTimer != null) {
            qrcodeTimer.purge();
            qrcodeTimer.cancel();
            qrcodeTimer = null;
        }
    }
}
